import { useCallback, useState, useMemo, useContext } from "react";

// import PixelarticonsMoreHorizontal from "~icons/pixelarticons/more-horizontal";
import PixelarticonsTrash from "~icons/pixelarticons/trash";

import { _ } from "~/lib/i18n";
import { formatDateShort } from "~/lib/util";
import { ManagerContext, DisplayModeContext } from "~/contexts";
import { BORDER_COLOR, LIKE_COLOR } from "~/constants";

import UserItem from "~/components/UserItem";
import IconButton from "~/components/IconButton";
import { Modal, ModalContext } from "~/components/modals/Modal";
import MoreIcon from "~/components/icons/MoreIcon";
import HeartIcon from "~/components/icons/HeartIcon";
import CommentIcon from "~/components/icons/CommentIcon";
import ShareIcon from "~/components/icons/ShareIcon";

const containerStyle = {
  display: "flex",
  flexDirection: "column" as "column",
  flexWrap: "nowrap" as "nowrap",
  gap: "0.3em",
  borderBottom: "1px solid " + BORDER_COLOR,
  padding: "0.3em 0 0.1em",
  overflow: "hidden",
};
const topStyle = {
  display: "flex",
  justifyContent: "space-between",
  gap: "0.5em",
};
const topActionsStyle = {
  display: "flex",
  gap: "0.3em",
  marginLeft: "auto", // 添加这行使按钮靠右对齐
};
const contentStyle = {
  display: "flex",
  flexDirection: "column" as "column",
  gap: "0.3em",
  overflowWrap: "break-word" as "break-word",
  wordBreak: "break-word" as "break-word",
  whiteSpace: "pre-wrap",
};
const menuIconStyle = { width: "1.2em", height: "auto" };
const compactActionsStyle = {
  display: "flex",
  flexDirection: "row" as "row",
  gap: "0.5em",
  padding: "0.5em 0",
  borderBottom: "1px solid " + BORDER_COLOR,
};

interface Props {
  children: React.ReactNode;
  authorId: string;
  authorName: string;
  isAdmin: boolean;
  date: number;
  deletePost: () => void;
  post?: Post | Reply;
  onComment?: () => void;
  onLike?: () => void;
  onShare?: () => void;
  [key: string]: any;
}

export default function BasePostItem({
  authorName,
  authorId,
  isAdmin,
  date,
  deletePost,
  post,
  onComment,
  onLike,
  onShare,
  children,
  ...props
}: Props) {
  props.style = { ...containerStyle, ...(props.style || {}) };
  const [isOpen, setOpen] = useState<boolean>(false);
  const manager = useContext(ManagerContext);
  const displayMode = useContext(DisplayModeContext);

  const onMenu = useCallback(() => {
    setOpen((isOpen) => !isOpen);
  }, []);

  const deleteAll = useCallback(() => {
    manager.deleteAll(authorId);
  }, [authorId]);

  const defaultOnLike = useCallback(() => {
    if (post) {
      // Check if it's a Post (has liked property) or Reply
      if ('liked' in post) {
        if (post.liked) {
          manager.unlike(post.id);
        } else {
          manager.like(post.id);
        }
      }
    }
  }, [post, manager]);

  const defaultOnComment = useCallback(() => {
    // This would normally be handled by the parent component
  }, []);

  const defaultOnShare = useCallback(() => {
    // This would normally be handled by the parent component
  }, []);

  const handleLike = onLike || defaultOnLike;
  const handleComment = onComment || defaultOnComment;
  const handleShare = onShare || defaultOnShare;

  // Check if post has likes and replies properties (Post type) or not (Reply type)
  const isPostType = post && 'likes' in post && 'replies' in post;

  let modal: any = null;
  if (isOpen) {
    modal = useMemo(() => {
      return (
        <ModalContext.Provider value={{ isOpen, setOpen }}>
          <Modal style={{ padding: "0.5em 1em" }}>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {displayMode === "compact" && post && isPostType && (
                <div style={compactActionsStyle}>
                  <IconButton
                    onClick={handleLike}
                    style={{ flex: 1 }}
                  >
                    {(post as Post).liked ? <HeartIcon filled={true} /> : <HeartIcon />}
                    {(post as Post).likes}
                  </IconButton>
                  <IconButton
                    onClick={handleComment}
                    style={{ flex: 1 }}
                  >
                    <CommentIcon />
                    {(post as Post).replies}
                  </IconButton>
                  <IconButton
                    onClick={handleShare}
                    style={{ flex: 1 }}
                  >
                    <ShareIcon />
                  </IconButton>
                </div>
              )}
              <IconButton
                onClick={deletePost}
                style={{
                  padding: "0.5em 0",
                  borderBottom: "1px solid " + BORDER_COLOR,
                }}
              >
                <PixelarticonsTrash />
                {_("Delete")}
              </IconButton>
              <IconButton onClick={deleteAll} style={{ padding: "0.5em 0" }}>
                <PixelarticonsTrash />
                {_("Delete all from user")}
              </IconButton>
            </div>
          </Modal>
        </ModalContext.Provider>
      );
    }, [deletePost, displayMode, handleComment, handleLike, handleShare, post, isPostType]);
  }

  return (
    <div {...props}>
      {modal}
      <div className="hpad08" style={topStyle}>
        <UserItem
          isAdmin={isAdmin}
          userId={authorId}
          name={authorName}
          subtitle={formatDateShort(date)}
        />
        {displayMode === "compact" && post && isPostType && (
          <div style={topActionsStyle}>
            <IconButton 
              style={{ color: (post as Post).liked ? LIKE_COLOR : undefined }}
              onClick={handleLike}
            >
              {(post as Post).liked ? <HeartIcon filled={true} /> : <HeartIcon />}
              {(post as Post).likes}
            </IconButton>
            <IconButton onClick={handleComment}>
              <CommentIcon />
              {(post as Post).replies}
            </IconButton>
          </div>
        )}
        <IconButton onClick={onMenu}>
          <MoreIcon style={menuIconStyle} />
        </IconButton>
      </div>
      <div style={contentStyle}>{children}</div>
    </div>
  );
}